package me.heizi.springboot.students

import java.security.MessageDigest
import kotlin.experimental.and
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.full.declaredMemberProperties


@Suppress("UNCHECKED_CAST")
fun <T:Any> T.updateNotNull(nullable:T):T {
    this::class.declaredMemberProperties.forEach {
        if (it is KMutableProperty1<*, out Any?>) (it as KMutableProperty1<T, Any?>).run {
            get(nullable)?.let { value -> set(this@updateNotNull, value) }
        }
    }
    return this
}

fun String.sha256() = MessageDigest
    .getInstance("SHA-256")
    .let {
        it.update(toByteArray(charset("UTF-8")))
        it.digest().hexString()
    }

fun ByteArray.hexString() = buildString {
    this@hexString.map {
        Integer.toHexString((it and Byte.MAX_VALUE).toInt())
    }.forEach {
        if (it.length == 1) append("0")
        append(it)
    }
}